<template>
  <view class="normal-login-container">
    <view class="logo-content align-center justify-center flex">
      <image style="width: 180rpx;height: 180rpx;" src="@/static/images/logo.png" mode="widthFix"></image>
      <text class="title"></text>
    </view>
    <view class="login-form-content">
      <view class="input-item flex align-center">
        <view class="iconfont icon-user icon"></view>
        <input v-model="loginForm.phone" class="input" type="number" placeholder="请输入手机号" maxlength="11" />
      </view>
      <view class="input-item flex align-center">
        <view class="iconfont icon-verification icon"></view>
        <input v-model="imgCode" class="input" type="text" placeholder="请输入图片验证码" maxlength="4" />
        <image :src="imgCodeUrl" @click="refreshImgCode" class="login-code-img" />
        <!-- #endif -->
        <!-- #ifdef MP-WEIXIN -->
        <view class="captcha-container" @click="refreshImgCode">
          <canvas
            canvas-id="captchaCanvas"
            class="captcha-canvas"
            :style="{width: '80px', height: '32px'}"
          ></canvas>
        </view>
        <!-- #endif -->
      </view>
      <view class="input-item flex align-center">
        <view class="iconfont icon-password icon"></view>
        <input v-model="loginForm.code" type="number" class="input" placeholder="请输入验证码" maxlength="6" style="width:60%" />
        <button class="get-code-btn" @click="getCode" :disabled="!canSendCode">{{ codeText }}</button>
      </view>

      <view class="action-btn">
        <button @click="handleLogin" class="login-btn cu-btn block bg-blue lg round" :disabled="!agree" :class="{ 'btn-disabled': !agree }">登录</button>
      </view>
      <view class="reg text-center" v-if="register">
        <text class="text-grey1">没有账号？</text>
        <text @click="handleUserRegister" class="text-blue">立即注册</text>
      </view>
      <view class="xieyi text-center xieyi-custom">
        <view class="custom-checkbox" :class="{ checked: agree }" @click="agree = !agree">
          <text v-if="agree" class="checkmark">✔</text>
        </view>
        <text :class="['xieyi-text', agree ? 'green' : 'grey']">
          我已认真阅读、理解并同意
          <text @click="handleUserAgrement" class="xieyi-link">《{{ globalConfig.appInfo.agreements[1].title }}》</text>
          <text @click="handlePrivacy" class="xieyi-link">《{{ globalConfig.appInfo.agreements[0].title }}》</text>
        </text>
      </view>
    </view>
    <view class="password-login-link" @click="goPasswordLogin" >使用密码登录</view>
    <!-- 其他登录方式分割线 -->
    <view class="other-login-divider">
      <view class="line"></view>
      <text class="other-login-text">其他登录方式</text>
      <view class="line"></view>
    </view>
    <!-- 其他登录方式按钮 -->
    <view class="other-login-btns">
      <view class="other-login-btn" @click="handleWxLogin">
        <image src="@/static/images/wechat.png" class="other-login-icon" />
      </view>
      <view class="other-login-btn" @click="handleAppleLogin">
        <image src="@/static/images/apple.png" class="other-login-icon" />
      </view>
    </view>
  </view>
</template>

<script>
import { getCodeImg, sendSmsCode, loginByPhone } from '@/api/login'

export default {
  data() {
    return {
      codeUrl: "",
      captchaEnabled: true,
      // 用户注册开关
      register: false,
      globalConfig: getApp().globalData.config,
      loginForm: {
        phone: '',
        code: ''
      },
      agree: false, // 新增，协议勾选状态
      codeText: '获取验证码',
      codeTime: 60,
      codeDisabled: false,
      imgCode: '',        // 用户输入的图片验证码
      imgCodeText: '',    // 生成的验证码文本
      imgCodeUrl: '',     // 生成的验证码图片base64
    }
  },
  computed: {
    canSendCode() {
      return (
        /^1[3-9]\d{9}$/.test(this.loginForm.phone) &&
        this.imgCode &&
        this.imgCode.toLowerCase() === this.imgCodeText.toLowerCase() &&
        !this.codeDisabled
      );
    }
  },
  mounted() {
    this.createImgCode();
  },
  // created() {
  //   this.getCode()
  // },
  methods: {
    // 用户注册
    handleUserRegister() {
      this.$tab.redirectTo('register')
    },
    // 隐私协议
    handlePrivacy() {
      let site = this.globalConfig.appInfo.agreements[0]
      this.$tab.navigateTo(`../common/webview/index?title=${site.title}&url=${site.url}`)
    },
    // 用户协议
    handleUserAgrement() {
      let site = this.globalConfig.appInfo.agreements[1]
      this.$tab.navigateTo(`../common/webview/index?title=${site.title}&url=${site.url}`)
    },
    onAgreeChange(e) {
      this.agree = e.detail.value.includes('agree');
    },
    // // 获取图形验证码
    // getCode() {
    //   getCodeImg().then(res => {
    //     this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
    //     if (this.captchaEnabled) {
    //       this.codeUrl = 'data:image/gif;base64,' + res.img
    //       this.loginForm.uuid = res.uuid
    //     }
    //   })
    // },
    // 生成随机验证码文本
    createImgCodeText() {
      const chars = 'ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';
      let code = '';
      for (let i = 0; i < 4; i++) {
        code += chars.charAt(Math.floor(Math.random() * chars.length));
      }
      this.imgCodeText = code;
    },
    // 生成验证码图片
    createImgCode() {
      this.createImgCodeText();

      // #ifdef H5
      // H5环境使用canvas生成验证码
      const canvas = document.createElement('canvas');
      canvas.width = 80;
      canvas.height = 32;
      const ctx = canvas.getContext('2d');
      ctx.fillStyle = '#f5f6f7';
      ctx.fillRect(0, 0, 80, 32);
      ctx.font = '20px Arial';
      ctx.fillStyle = '#333';
      ctx.textBaseline = 'middle';
      ctx.fillText(this.imgCodeText, 15, 16);
      // 干扰线
      for (let i = 0; i < 3; i++) {
        ctx.strokeStyle = '#'+Math.floor(Math.random()*0xffffff).toString(16);
        ctx.beginPath();
        ctx.moveTo(Math.random()*80, Math.random()*32);
        ctx.lineTo(Math.random()*80, Math.random()*32);
        ctx.stroke();
      }
      this.imgCodeUrl = canvas.toDataURL();
      // #endif

      // #ifdef MP-WEIXIN
      // 微信小程序环境使用canvas组件生成验证码
      this.$nextTick(() => {
        const ctx = uni.createCanvasContext('captchaCanvas', this);
        // 设置背景
        ctx.setFillStyle('#f5f6f7');
        ctx.fillRect(0, 0, 80, 32);

        // 设置文字样式
        ctx.setFillStyle('#333');
        ctx.setFontSize(16);
        ctx.setTextBaseline('middle');

        // 绘制验证码文字
        ctx.fillText(this.imgCodeText, 15, 16);

        // 绘制干扰线
        for (let i = 0; i < 3; i++) {
          ctx.setStrokeStyle('#' + Math.floor(Math.random() * 0xffffff).toString(16));
          ctx.beginPath();
          ctx.moveTo(Math.random() * 80, Math.random() * 32);
          ctx.lineTo(Math.random() * 80, Math.random() * 32);
          ctx.stroke();
        }

        // 绘制到canvas
        ctx.draw();
      });
      // #endif
    },
    // 点击图片刷新
    refreshImgCode() {
      this.createImgCode();
      this.imgCode = '';
    },
    // 登录方法
    async handleLogin() {
      if (!this.agree) {
        this.$modal.msgError("请先同意协议");
        return;
      }
      if (!/^1[3-9]\d{9}$/.test(this.loginForm.phone)) {
        this.$modal.msgError("请输入正确的手机号");
        return;
      }
      if (!/^\d{4,6}$/.test(this.loginForm.code)) {
        this.$modal.msgError("请输入验证码");
        return;
      }
      if (!this.imgCode) {
        this.$modal.msgError("请输入图片验证码");
        return;
      }
      if (this.imgCode.toLowerCase() !== this.imgCodeText.toLowerCase()) {
        this.$modal.msgError("图片验证码错误");
        this.refreshImgCode();
        return;
      }
      this.$modal.loading("登录中，请耐心等待...");
      loginByPhone(this.loginForm.phone, this.loginForm.code).then(res => {
        this.$modal.closeLoading();
        console.log('登录响应:', res);
        if (res.code === 200 && res.data && res.data.access_token) {
          // 设置token到store和storage
          if (this.$store && this.$store.commit) {
            this.$store.commit('user/SET_TOKEN', res.data.access_token);
          }
          uni.setStorageSync('App-Token', res.data.access_token);
          console.log('Token已设置:', res.data.access_token);
          this.loginSuccess();
        } else {
          this.$modal.msgError(res.msg || "登录失败");
        }
      }).catch((error) => {
        console.error('登录请求失败:', error);
        this.$modal.closeLoading();
        this.$modal.msgError("网络错误");
      });
    },
    getCode() {
      // 此处不再校验图片验证码，按钮已控制
      this.codeDisabled = true;
      this.codeText = `${this.codeTime}s`;
      sendSmsCode(this.loginForm.phone).then(res => {
        if (res.code === 200) {
          this.$modal.msgSuccess("验证码已发送");
          let timer = setInterval(() => {
            this.codeTime--;
            this.codeText = `${this.codeTime}s`;
            if (this.codeTime <= 0) {
              clearInterval(timer);
              this.codeText = '获取验证码';
              this.codeTime = 60;
              this.codeDisabled = false;
            }
          }, 1000);
        } else {
          this.$modal.msgError(res.msg || "发送失败");
          this.codeText = '获取验证码';
          this.codeTime = 60;
          this.codeDisabled = false;
        }
      }).catch(() => {
        this.$modal.msgError("网络错误");
        this.codeText = '获取验证码';
        this.codeTime = 60;
        this.codeDisabled = false;
      });
    },
    // 登录成功后，处理函数
    loginSuccess(result) {
      // 设置用户信息
      if (!this.$store || !this.$store.dispatch) {
        console.error('Store不可用，直接跳转')
        this.$tab.reLaunch('/pages/mine/index')
        return
      }

      try {
        this.$store.dispatch('user/GetInfo').then(res => {
          console.log('登录成功，用户信息获取完成')
          this.$tab.reLaunch('/pages/mine/index')
        }).catch(error => {
          console.error('获取用户信息失败:', error)
          this.$tab.reLaunch('/pages/mine/index')
        })
      } catch (error) {
        console.error('调用GetInfo时出错:', error)
        this.$tab.reLaunch('/pages/mine/index')
      }
      this.$store.dispatch('GetInfo').then(res => {
        this.$tab.reLaunch('/pages/index')
      })
    },
    handleWxLogin() {
      this.$modal.msg('微信登录功能开发中');
    },
    handleAppleLogin() {
      this.$modal.msg('Apple登录功能开发中');
    },
   goPasswordLogin() {
			this.$tab.navigateTo('/pages/password')
   }
  }
}
</script>

<style lang="scss" scoped>
page {
  background-color: #ffffff;
}

.normal-login-container {
  width: 100%;

  .logo-content {
    width: 100%;
    font-size: 21px;
    text-align: center;
    padding-top: 8%;

    image {
      border-radius: 4px;
    }

    .title {
      margin-left: 10px;
    }
  }

  .login-form-content {
    text-align: center;
    margin: 20px auto;
    margin-top: 15%;
    width: 80%;

    .input-item {
      margin: 20px auto;
      background-color: #f5f6f7;
      height: 45px;
      border-radius: 20px;

      .icon {
        font-size: 38rpx;
        margin-left: 10px;
        color: #999;
      }

      .input {
        width: 100%;
        font-size: 14px;
        line-height: 20px;
        text-align: left;
        padding-left: 15px;
      }

    }

    .login-btn {
      margin-top: 40px;
      height: 45px;
    }

    .reg {
      margin-top: 15px;
    }

    .xieyi {
      color: #333;
      margin-top: 20px;
    }

    .login-code {
      height: 38px;
      float: right;

      .login-code-img {
        height: 38px;
        position: absolute;
        margin-left: 10px;
        width: 200rpx;
      }
    }

    .login-btn:disabled,
    .btn-disabled {
      background: #b0c4de !important;
      color: #fff !important;
      opacity: 0.7;
    }
    .get-code-btn {
      margin-left: 10px;
      height: 32px;
      line-height: 32px;
      padding: 0 10px;
      font-size: 13px;
      border-radius: 16px;
      background: #f5f6f7;
      color: #007aff;
      border: none;
    }
  }
}

.password-login-link {
  text-align: center;
  color: #666;
  font-size: 16px;
  margin: 18px 0 0 0;
  cursor: pointer;
}

.xieyi-custom {
  display: flex;
  align-items: flex-start;
  justify-content: flex-start;
  margin-top: 20px;

  .custom-checkbox {
    width: 20px;
    height: 20px;
    border-radius: 50%;
    border: 2px solid #bbb;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 8px;
    transition: border-color 0.2s;
    font-size: 16px;
    cursor: pointer;
    box-sizing: border-box;
    .checkmark {
      color: #e43d33;
      font-size: 16px;
      font-weight: bold;
    }
  }
  .custom-checkbox.checked {
    border-color: #4caf50; // 绿色
    background: #fff;
  }
  .custom-checkbox .checkmark {
    color: #4caf50; // 绿色
  }
  .xieyi-text.red {
    color: #4caf50; // 绿色
  }
  .xieyi-link {
    color: #4caf50; // 绿色
  }
  .xieyi-text {
    font-size: 15px;
    line-height: 1.5;
    &.grey {
      color: #999;
    }
    &.red {
      color: #e43d33;
    }
    .xieyi-link {
      color: #e43d33;
      margin: 0 2px;
      cursor: pointer;
    }
  }
}
.other-login-divider {
  display: flex;
  align-items: center;
  margin: 40px 0 20px 0;
  .line {
    flex: 1;
    height: 1px;
    background: #eee;
  }
  .other-login-text {
    margin: 0 12px;
    color: #999;
    font-size: 14px;
  }
}
.other-login-btns {
  display: flex;
  justify-content: center;
  gap: 32px;
  margin-bottom: 20px;
  .other-login-btn {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    background: #f5f6f7;
    display: flex;
    align-items: center;
    justify-content: center;
    .other-login-icon {
      width: 32px;
      height: 32px;
    }
  }
}
.login-code-img {
  width: 80rpx;
  height: 32rpx;
  margin-left: 10rpx;
  vertical-align: middle;
}

/* 微信小程序验证码canvas样式 */
.captcha-container {
  margin-left: 10rpx;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
}

.captcha-canvas {
  display: block;
  width: 80px;
  height: 32px;
}
</style>
